package com.game.server;

import java.util.concurrent.ConcurrentHashMap;

import com.game.action.GetGameListAction;
import com.game.action.HeartBreakAction;
import com.game.action.LoginAction;
import com.game.action.ValidateAction;

class ActionMap {

	ConcurrentHashMap<String, Action> map;

	protected void initActionMap() {
		map = new ConcurrentHashMap<String, Action>();
		addAction(getClassName(GetGameListAction.class.getName()));
		addAction(getClassName(HeartBreakAction.class.getName()));
		addAction(getClassName(LoginAction.class.getName()));
		addAction(getClassName(ValidateAction.class.getName()));
	}

	protected Action getAction(String key) {
		Action action = map.get(key);
		if (action == null) {
			action = addAction(key);
		}
		return action;
	}

	private String getClassName(String name) {
		int index = name.lastIndexOf(".");
		if (index > 0) {
			return name.substring(index + 1);
		}
		return name;
	}

	private Action addAction(String actionName) {
		Action action = actionFromString(actionName);
		if (action != null) {
			map.put(actionName, action);
		}
		return action;
	}

	private Action actionFromString(String actionName) {
		String fullName = "com.game.action." + actionName;
		try {
			return (Action) Class.forName(fullName).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
